<?php
/**
 * Application Common Component
 * @copyright  duonght6255@setacinq.com.vn
 *
 */
App::uses('Component', 'Controller');

class CommonComponent extends Component{

	/**
	 *
	 * @param unknown $str
	 * @return boolean|mixed
	 */
	public static function ConvertToUnicode($str){
		$vietnamese = array(
				"à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă",
				"ằ","ắ","ặ","ẳ","ẵ",
				"è","é","ẹ","ẻ","ẽ","ê","ề" ,"ế","ệ","ể","ễ",
				"ì","í","ị","ỉ","ĩ",
				"ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
				,"ờ","ớ","ợ","ở","ỡ",
				"ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
				"ỳ","ý","ỵ","ỷ","ỹ",
				"đ",
				"À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
				,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
				"È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
				"Ì","Í","Ị","Ỉ","Ĩ",
				"Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
				,"Ờ","Ớ","Ợ","Ở","Ỡ",
				"Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
				"Ỳ","Ý","Ỵ","Ỷ","Ỹ",
				"Đ","ê","ù","à"
		);

		$unicode = array(
				"a","a","a","a","a","a","a","a","a","a","a"
				,"a","a","a","a","a","a",
				"e","e","e","e","e","e","e","e","e","e","e",
				"i","i","i","i","i",
				"o","o","o","o","o","o","o","o","o","o","o","o"
				,"o","o","o","o","o",
				"u","u","u","u","u","u","u","u","u","u","u",
				"y","y","y","y","y",
				"d",
				"A","A","A","A","A","A","A","A","A","A","A","A"
				,"A","A","A","A","A",
				"E","E","E","E","E","E","E","E","E","E","E",
				"I","I","I","I","I",
				"O","O","O","O","O","O","O","O","O","O","O","O"
				,"O","O","O","O","O",
				"U","U","U","U","U","U","U","U","U","U","U",
				"Y","Y","Y","Y","Y",
				"D","e","u","a"
		);

		return str_replace($vietnamese, $unicode, $str);
	}

	/**
	 * Seo title
	 *
	 * @param string $string
	 * @return string
	 */
	public static function rewriteTitle($string, $keyReplace = '/') {
		$string = self::ConvertToUnicode($string);

		$string = trim(preg_replace("/[^A-Za-z0-9]/i"," ",$string)); // khong dau
		$string = str_replace(" ", "-", $string);
		$string = str_replace("--", "-", $string);
		$string = str_replace("--", "-", $string);
		$string = str_replace("--", "-", $string);
		$string = str_replace("--", "-", $string);
		$string = str_replace("--", "-", $string);
		$string = str_replace("--", "-", $string);
		$string = str_replace("--", "-", $string);
		$string = str_replace($keyReplace, "-", $string);

		return strtolower(trim($string, '-'));
	}

	/**
	 * Format category follow parent and child
	 * @param array $categories
	 * @return array
	 */
	public static function formatCategory($categories = array()){
		foreach ($categories as &$category) {
			if($category['cat_level'] >= 1){
				$category['cat_name'] = str_repeat('---',$category['cat_level']).$category['cat_name'];
			}
		}
		return $categories;
	}

	/**
	 * Xử lý cùng độ dài ở dạng text
	 * ==> 1 ==> 001; ==> 2 ==> 002 ....
	 * @param unknown $length
	 * @param unknown $number
	 * @return string
	 */
	public static function sameLengthTextNumber($length, $number){
		if($length > strlen($number)){
			$add_length = $length - strlen($number);
			$number = str_repeat('0', $add_length).$number;
		}

		return $number;
	}

	/**
	 *
	 * @param array $items
	 * @param string $field
	 * @param string $key
	 * @return Ambigous <multitype:, unknown>
	 */
	public static function classifyArray($items, $field, $key = false){
		$result = array();
		foreach ($items as $item) {
			if(!empty($key)){
				$result[$item[$field]][$item[$key]] = $item;
			}else {
				$result[$item[$field]][] = $item;
			}
		}

		return $result;
	}

	/**
	 *
	 * @param array $categories
	 * @return Ambigous <multitype:, unknown>
	 */
	public static function menuGroupByPositionAndLevel($categories = array()){
		$result = array();
		if(!empty($categories)){
			foreach ($categories as $category){
				if($category['mnu_level'] == 1){
					$result[$category['mnu_position']]['level_'.$category['mnu_level']][$category['id']] = $category;
				}
				if($category['mnu_level'] != 1){
					$result[$category['mnu_position']]['level_'.$category['mnu_level']][$category['mnu_parent_id']][$category['id']] = $category;
				}
			}
		}
		return $result;
	}

	/**
	 * Cut string
	 * @param string $str
	 * @param number $len
	 * @param string $more
	 * @return string
	 */
	public static function cutstr($str, $len, $more = true) {
		if ($str=="" || $str==NULL) {
			return $str;
		}

		if (strlen($str) <= $len) {
			return $str;
		}

		$str = strip_tags($str);
		$str = trim($str);
		$str = substr($str,0,$len);
		if ($str != "") {
			if (!substr_count($str," ")) {
				if ($more) {
					$str .= " ...";
				}
				return $str;
			}

			while(strlen($str) && ($str[strlen($str)-1] != " ")) {
				$str = substr($str,0,-1);
			}

			$str = substr($str,0,-1);

			if ($more) {
				$str .= " ...";
			}
		}

		return $str;
	}

	public static function createSqlSearch($keyword, $field) {
		$min_character          = 1;
		$max_keyword            = 5;
		$quote_space            = " + ";
		$max_keyword_length     = 100;
		$min_fulltext_character = 5;
		$array_keyword          = array();
		$sql_keyword            = " AND ";

		//Loại bỏ ' để chống sql injection
		$keyword = str_replace("\'","'",$keyword);
		$keyword = str_replace("'","''",$keyword);
		$keyword = self::ConvertToUnicode($keyword);
		$keyword = mb_strtolower($keyword, "UTF-8");

		if (strlen($keyword) > $max_keyword_length) {
			$keyword = substr($keyword, 0, $max_keyword_length);
		}

		preg_match_all('/' . preg_quote('&quot;') .'(.*?)' . preg_quote('&quot;') .'/is', $keyword, $quote);

		$j = -1;
		//nếu tồn tại từ khóa trong ngoặc kép
		if(isset($quote[0][0])){
			if(isset($quote[1][0])){
				for($i=0; $i < count($quote[1]); $i++){
					if (strlen(trim($quote[1][$i])) > $min_character){
						$j++;
						$array_keyword[$j][0] = trim($quote[1][$i]);

						if (strpos($array_keyword[$j][0], " ") === false && mb_strlen($array_keyword[$j][0],"utf-8") >= $min_fulltext_character && strpos($array_keyword[$j][0], "-") === false) {
							$array_keyword[$j][1] = "F";
						}
						//Nếu không kiều thường kiểu LIKE
						else{
							$array_keyword[$j][1] = "L";
						}
					}

					if ($j >= $max_keyword) break;
				}//end for
			}

			$keyword = str_replace($quote[0],'',$keyword);
		}

		if ($j <= $max_keyword){
			$array_temp = preg_split('|[' . preg_quote($quote_space) . ']|Ui', $keyword);
			for($i = 0; $i < count($array_temp); $i++){
				if (strlen(trim($array_temp[$i])) > $min_character){
					$j++;
					//gán từ khóa
					$array_keyword[$j][0] = trim($array_temp[$i]);
					if (mb_strlen($array_keyword[$j][0], "utf-8") >= $min_fulltext_character && !is_numeric($array_keyword[$j][0]) && strpos($array_keyword[$j][0], "-") === false) {
						$array_keyword[$j][1] = "F";
					}
					else{
						$array_keyword[$j][1] = "L";
					}

					if ($j >= $max_keyword) break;

				}//end if

			}//end for
		}//if ($j <= $this->max_keyword)

		//Tạo query cho từ khóa tìm kiếm
		for ($i = 0; $i < count($array_keyword); $i++){
			$sql_keyword .= $field . " LIKE '%" . $array_keyword[$i][0] . "%' AND ";
		}

		$sql_keyword .= "1 ";

		return $sql_keyword;
	}
}
